package org.dei.perla.rockfall.utils.db;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.dei.perla.parser.expressions.ConstantCastException;
import org.dei.perla.parser.expressions.ConstantTimestamp;
import org.dei.perla.sys.dbutils.DBDumper;
import org.dei.perla.sys.llqruntime.datastructures.Record;
import org.dei.perla.utils.logger.SimpleLogger;

public class DeviceLogDatabaseDump extends DBDumper {
	
	private PreparedStatement pStmMppt;
	
	@Override
	protected void closeStatements() {
		SimpleLogger.log(this.getClass(), "Effettuto commit su DB");
		try {
			this.pStmMppt.executeBatch();
			conn.commit();
			pStmMppt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	@Override
	protected void initStatements() {
		try {
			conn.setAutoCommit(false);
			pStmMppt = conn.prepareStatement("INSERT INTO dspicLog " +
					"(TIMESTAMP, NODE_ID, UPTIME, DATA_TIMEOUT, PARAMETER_TIMEOUT, ROUND) " +
					"VALUES	(?, ?, ?, ?, ?, ?)");
		} catch (SQLException ex) {
			SimpleLogger.log(this.getClass(), "SQLException: " + ex.getMessage());
			SimpleLogger.log(this.getClass(), "SQLState: " + ex.getSQLState());
			SimpleLogger.log(this.getClass(), "VendorError: " + ex.getErrorCode());
		}
	}

	@Override
	protected void sendToDB(Record tRecord) {
		if (conn == null) {
			SimpleLogger.log(this.getClass(), "Impossibile memorizzare su DB, errore durante la connessione al DB");
			return;
		}
		try {
			pStmMppt.setLong(1, ((ConstantTimestamp)tRecord.getField("TIMESTAMP")).getValueTimestamp());
			pStmMppt.setInt(2, tRecord.getField("NODE_ID").getValueInt());
			pStmMppt.setInt(3, tRecord.getField("UPTIME").getValueInt());
			pStmMppt.setInt(4, tRecord.getField("DATA_TIMEOUT").getValueInt());
			pStmMppt.setInt(5, tRecord.getField("PARAMETER_TIMEOUT").getValueInt());
			pStmMppt.setInt(6, tRecord.getField("ROUND").getValueInt());
			pStmMppt.addBatch();
			SimpleLogger.log(this.getClass(), "Added Record to batch");
		} catch (SQLException e) {
			SimpleLogger.log(this.getClass(), "Errore durante l'immissione dei dati nel DB: " + e.getMessage());
		} catch (ConstantCastException e) {
			SimpleLogger.log(this.getClass(), "Errore durante l'immissione dei dati nel DB, " +
					"cast Constant non supportato: " + e.getMessage());
		}
	}
}
